#include "server.h"

Server::Server()
{
	//创建服务器
	tcpServer = new QTcpServer();
	//开始监听
	if(!tcpServer->listen(QHostAddress::Any, 6789))
	{
		tcpServer->close();
		return;
	}
	ipLabel = new QLabel(tr("服务器IP"));
	portLabel = new QLabel(tr("端口"));
	ipLineEdit = new QLineEdit();
	portLineEdit = new QLineEdit();
	receiveLabel = new QLabel(tr("接收数据"));
	sendLabel = new QLabel(tr("发送数据"));
	sendTextEdit = new QTextEdit();
	receiveTextEdit = new QTextEdit();
	sendButton = new QPushButton(tr("发送"));
        ipLabel->setText((QString)tcpServer->serverAddress());
	QHBoxLayout *hLay1 = new QHBoxLayout();
	hLay1->addWidget(ipLabel);
	hLay1->addWidget(ipLineEdit);
	hLay1->addWidget(portLabel);
	hLay1->addWidget(portLineEdit);
	QHBoxLayout *hLay2 = new QHBoxLayout();
	hLay2->addWidget(sendLabel);
	hLay2->addWidget(receiveLabel);
	QHBoxLayout *hLay3 = new QHBoxLayout();
	hLay3->addWidget(sendTextEdit);
	hLay3->addWidget(receiveTextEdit);
	QVBoxLayout *mainLay = new QVBoxLayout();
	mainLay->addLayout(hLay1);
	mainLay->addLayout(hLay2);
	mainLay->addLayout(hLay3);
	mainLay->addWidget(sendButton);
	
	connect(tcpServer, SIGNAL(newConnection()), this, SLOT(enableSend()));
	connect(sendButton, SIGNAL(clicked()), this, SLOT(sendMessage()));
	setLayout(mainLay);
	setWindowTitle(tr("TCP服务器"));
	sendButton->setDisabled(true);

}

void Server::enableSend()
{
	//建立链接
	qDebug()<<"new connection!!!";
	sendButton->setEnabled(true);
	socket = tcpServer->nextPendingConnection();
}
void Server::sendMessage()
{
	//初始化数据
	QByteArray block;
	QDataStream out(&block, QIODevice::ReadWrite);
	out.device()->seek(0);
	out<<sendTextEdit->toPlainText();

	qDebug()<<"send";
	if(socket!=NULL)
	{
		connect(socket, SIGNAL(disconnected()), socket, SLOT(deleteLater()));
		socket->write(block);	
	}
	if(socket==NULL)
		qDebug()<<"failed";
}
